package com.az.alibaba.downloader;

import hirondelle.date4j.DateTime;

import java.io.IOException;
import java.util.Random;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHelper {

	private static final Logger log = LoggerFactory.getLogger(HttpHelper.class);
	private static Random random = new Random(System.currentTimeMillis());

	private static int redirectNum = 0;
	private static int maxRedirect = 20;
	private static boolean first = true;

	private static RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).setMaxRedirects(1).setRedirectsEnabled(false)
			.build();

	private static HttpGet getHttpGet(String url) {
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("User-Agent",
				"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36");
		httpGet.setHeader("Pragma", "no-cache");
		httpGet.setHeader("Referer", url);
		httpGet.setHeader("Cache-Control", "no-cache");
		httpGet.setConfig(config);
		return httpGet;

	}

	public static Document get(String url, int times) {
		
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {

			if (!first) {
				log.info("sleep a while");
				Integer seconds = Integer.valueOf(3);
				Integer delay = random.nextInt(seconds);
				delay = (seconds + delay) * 1000;
				log.info("sleep time:{}", delay);
				Thread.sleep(delay);
				log.info("wake after rest a while");
				first = false;
			} else {
				first = false;
			}

			response = null;
			// ===========获取一个关键词============

			HttpGet httpGet = getHttpGet(url);

			log.info("开始http请求,获取:{}", url);
			response = client.execute(httpGet);

			if (response.getStatusLine().getStatusCode() == 200) {
				redirectNum = 0;
				log.info("获取entity");
				HttpEntity entity = response.getEntity();
				do {
					if (entity == null) {
						log.error("entity is null");
						break;
					}
					log.info("location的entity转换成document");
					Document doc = Jsoup.parse(EntityUtils.toString(entity));
					return doc;
				} while (false);

			} else if (response.getStatusLine().getStatusCode() == 403 || response.getStatusLine().getStatusCode() == 301
					|| response.getStatusLine().getStatusCode() == 302) {
				log.info("http请求location返回:{}", response.getStatusLine().getStatusCode());
				do{
					if(response.getStatusLine().getStatusCode() != 301 || times > 2){
						break;
					}
					Header locationHead = response.getFirstHeader("Location");
					if(locationHead == null){
						break;
					}
					String location = locationHead.getValue();
					if(StringUtils.isBlank(location)){
						break;
					}
					if(location.indexOf("contactinfo.html") < 0){
						break;
					}
					return get(location, ++times);
					
				}while(false);
				
				redirectNum++;
				log.info("redirectNum:{}", redirectNum);
				if (redirectNum > maxRedirect) {
					try {
						DateTime now = DateTime.now(TimeZone.getTimeZone("Asia/Shanghai"));
						log.info("返回{},sleep@time:{}", response.getStatusLine().getStatusCode(), now.format("YYYY-MM-DD hh:mm:ss"));
						Thread.sleep(1000 * 60 * 15);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					DateTime now = DateTime.now(TimeZone.getTimeZone("Asia/Shanghai"));
					log.info("返回{},wake@time:{}", response.getStatusLine().getStatusCode(), now.format("YYYY-MM-DD hh:mm:ss"));
				}
			}

		} catch (Exception e) {
			log.error("出错啦!!There is an error:", e);
		} finally {
			if (response != null) {
				log.info("close response");
				try {
					response.close();
				} catch (IOException e) {
					log.info("", e);
				}
			}
		}

		return null;
	}
}
